package hu.u_szeged.inf.ovrt.filelister.commands;

import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.ERROR;
import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.INFO;
import hu.u_szeged.inf.ovrt.filelister.core.beans.ApplicationState;
import hu.u_szeged.inf.ovrt.filelister.ui.UserInterface;

import java.io.File;
import java.util.Map;

/**
 * Change directory module.
 */
public class Cd extends AbstractCommand {

    /**
     * Constructor, that sets user interface.
     * @param ui user interface.
     */
    public Cd(UserInterface ui) {
        super(ui);
    }

    @Override
    public void execute(ApplicationState state, Map<String, String> parameters) {
        String folder = "";
        File tempFile = null;
        String tempString = null;
        String[] pathBits;
        boolean ok = true;

        if (parameters.containsKey("default")) {
            folder = parameters.get("default");
        }

        //trim slashes from edges
        folder = folder.replace('/', '\\');
        if (folder.startsWith("\\")) {
            folder = folder.substring(1);
        }
        if (folder.endsWith("\\")) {
            folder = folder.substring(0, folder.length() - 1);
        }

        //to avoid '..'s in the path, iterate through the path manually
        tempFile = new File(state.getFile().getAbsolutePath());
        pathBits = folder.split("\\\\");

        for (String bit : pathBits) {
            //parent folder
            if ("..".equals(bit)) {
                tempFile = tempFile.getParentFile();
                if (tempFile == null) {
                    getUi().printLn("Invalid path", ERROR);
                    ok = false;
                    break;
                }

                //same folder, do nothing
            } else if (".".equals(bit)) {
                continue;

            } else {
                tempString = tempFile.getAbsolutePath() + "\\" + bit;
                tempFile = new File(tempString);

                if (!tempFile.exists()) {
                    getUi().printLn("Not found: " + tempString, ERROR);
                    ok = false;
                    break;
                }
            }
        }

        if (ok) {
            state.setFile(tempFile);
            getUi().printLn("Directory changed to: " + tempFile.toString(), INFO);
        }
    }
}
